package com.masterclient.app.modules.bridge;


import android.Manifest;
import android.content.Intent;
import android.text.TextUtils;
import android.webkit.JavascriptInterface;
import com.eoner.baselib.utils.sp.SPUtils;
import com.eoner.baselibrary.utils.IntentUtil;
import com.eoner.baselibrary.widget.PermissionDialog;
import com.eoner.common.config.Config;
import com.google.gson.Gson;
import com.masterclient.app.R;
import com.masterclient.app.base.CaptureActivity;
import com.masterclient.app.base.ConfirmDialog;
import com.masterclient.app.businessmodule.usermodule.login.index.QuickLoginActivity;
import com.masterclient.app.utils.CommonUtil;
import com.masterclient.app.widget.ShareNewCommonDialog;
import com.tbruyelle.rxpermissions2.RxPermissions;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Map;

import wendu.dsbridge.OnReturnValue;

public class JsOfFragmentApi {

    private RxPermissions rxPermissions;
    private BridgeFragment bridgeFragment;
    private boolean isResume;

    public JsOfFragmentApi(BridgeFragment bridgeFragment) {
        this.bridgeFragment = bridgeFragment;
        rxPermissions = new RxPermissions(bridgeFragment.getActivity());
        isResume = false;
    }

    /**
     * 获取Token
     */
    @JavascriptInterface
    public String getToken(Object msg) {
        String token = SPUtils.getInstance().getString(Config.CUSTOMER_TOKEN);
        if (TextUtils.isEmpty(token)){
            token = "";
        }
        return token;
    }

    /**
     * 扫码
     */
    @JavascriptInterface
    public void scan(Object msg) {
        rxPermissions = new RxPermissions(bridgeFragment.getActivity());
        boolean hasPermissions = rxPermissions.isGranted(Manifest.permission.CAMERA);
        if (!hasPermissions){
            new PermissionDialog(bridgeFragment.getActivity(), "开启摄像头权限","获取摄像头和相册权限以便扫码，请在下一个页面点击“允许”",
                    R.mipmap.icon_permission_phone,this::requestPermissions).show();
        }else {
            Intent intent = new Intent(bridgeFragment.getActivity(), CaptureActivity.class);
            try {
                bridgeFragment.getActivity().startActivityForResult(intent, 111);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 扫码结果回调给H5
     */
    public void scanResult(String code){
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("mobile",code);
            bridgeFragment.dwebView.callHandler("scanResult", new Object[]{code}, new OnReturnValue<String>() {
                @Override
                public void onValue(String retValue) {
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void requestPermissions(){
        rxPermissions
                .requestEach(Manifest.permission.CAMERA)
                .subscribe(permission -> { // will emit 2 Permission objects
                    if (permission.granted) {
                        // `permission.name` is granted !
                        Intent intent = new Intent(bridgeFragment.getActivity(), CaptureActivity.class);
                        try {
                            bridgeFragment.getActivity().startActivityForResult(intent, 111);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else if (permission.shouldShowRequestPermissionRationale) {
                        // Denied permission without ask never again
                    } else {
                        // Denied permission with ask never again
                        // Need to go to the settings
                    }
                });
    }

    /**
     * 打开二级Web页
     */
    @JavascriptInterface
    public void openWeb(Object msg) {
        try {
            JSONObject object = new JSONObject(msg.toString());
            String target = object.optString("url");
            String targetID = object.optString("targetID");
            CommonUtil.goAnyWhere(bridgeFragment.getActivity(), target, targetID, "", "", "");
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 打开地图弹窗
     */
    @JavascriptInterface
    public void openMap(Object msg) {
        Map<String,String> map = new Gson().fromJson(msg.toString(),Map.class);
        if ( bridgeFragment.dialog != null){
            bridgeFragment.setDialog(map);
        }
    }

    /**
     * 打开登陆页
     */
    @JavascriptInterface
    public void goLogin(Object msg) {
        Intent intent = new Intent(bridgeFragment.getActivity(), QuickLoginActivity.class);
        intent.putExtra("intentSource","");
        bridgeFragment.getActivity().startActivity(intent);
    }

    /**
     * 打开分享Dialog
     */
    @JavascriptInterface
    public void addNavShareButton(Object obj) {
        try {
            JSONObject object = new JSONObject(obj.toString());
            int type = object.optInt(" type");
            if (0 == type){
                String url = object.optString("url");
                String image = object.optString("image");
                String title = object.optString("title");
                String desc = object.optString("desc");
                ShareNewCommonDialog h5Dialog = new ShareNewCommonDialog(bridgeFragment.getActivity(),true);
                h5Dialog.show();
                h5Dialog.setShareLinkData(url,title,desc,image);
            }else {
                String name = object.optString("name");
                String image = object.optString("image");
                String shareUrl = object.optString("share_url");
                String showMan = object.optString("show_man");
                String showPhone = object.optString("show_phone");
                String categoryName = object.optString("category_name");
                String iconUrl = object.optString("icon_url");
                ShareNewCommonDialog h5Dialog = new ShareNewCommonDialog(bridgeFragment.getActivity(),false);
                h5Dialog.show();
                h5Dialog.setShareData(name,image,shareUrl,showMan,showPhone,categoryName,iconUrl);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @JavascriptInterface
    public String deleteNavShareButton(Object msg) {
        String token = SPUtils.getInstance().getString(Config.CUSTOMER_TOKEN);
        if (TextUtils.isEmpty(token)){
            token = "";
        }
        return token;
    }

    @JavascriptInterface
    public void joinSuccess(Object msg) {
    }

    /**
     * 拨打电话
     */
    @JavascriptInterface
    public void callPhone(Object msg) {
        try {
            JSONObject object = new JSONObject(msg.toString());
            String phone = object.getString("phone");
            ConfirmDialog dialog = new ConfirmDialog(bridgeFragment.getActivity(), "是否拨打电话", null, phone, "取消", "确定", "#FF6809");
            dialog.setOnChooseListerner(new ConfirmDialog.OnChooseListerner() {
                @Override
                public void cancel() {
                    dialog.dismiss();
                }

                @Override
                public void confirm() {
                    IntentUtil.toPhoneApp(bridgeFragment.getActivity(), phone);
                    dialog.dismiss();
                }
            });
            dialog.show();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 扫码签到
     */
    String eventId = "";
    @JavascriptInterface
    public void scanCheckin(Object msg) {
        try {
            JSONObject object = new JSONObject(msg.toString());
            eventId = object.getString("event_id");
            rxPermissions = new RxPermissions(bridgeFragment.getActivity());
            boolean hasPermissions = rxPermissions.isGranted(Manifest.permission.CAMERA);
            if (!hasPermissions) {
                new PermissionDialog(bridgeFragment.getActivity(), "开启摄像头权限", "获取摄像头和相册权限以便扫码，请在下一个页面点击“允许”",
                        R.mipmap.icon_permission_phone, this::requestCameraPermissions).show();
            } else {
                Intent intent = new Intent(bridgeFragment.getActivity(), CaptureActivity.class);
                intent.putExtra("eventId",eventId);
                try {
                    bridgeFragment.getActivity().startActivityForResult(intent, 111);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void requestCameraPermissions() {
        rxPermissions
                .requestEach(Manifest.permission.CAMERA)
                .subscribe(permission -> { // will emit 2 Permission objects
                    if (permission.granted) {
                        // `permission.name` is granted !
                        Intent intent = new Intent(bridgeFragment.getActivity(), CaptureActivity.class);
                        intent.putExtra("eventId",eventId);
                        try {
                            bridgeFragment.getActivity().startActivityForResult(intent, 111);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else if (permission.shouldShowRequestPermissionRationale) {
                        // Denied permission without ask never again
                    } else {
                        // Denied permission with ask never again
                        // Need to go to the settings
                    }
                });
    }
}
